package com.linkoog.devtools.json.file_editer.editer.ui.jsonTree.action;

import com.fasterxml.jackson.databind.JsonNode;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.treeStructure.Tree;
import com.linkoog.devtools.json.file_editer.editer.ui.JackJsonTreeNode;
import org.jetbrains.annotations.NotNull;

import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.util.Enumeration;
import java.util.Objects;

public class ExpandMultiAction extends AnAction {

    private final Tree tree;

    public ExpandMultiAction(Tree tree) {
        super("完全展开..");
        this.tree = tree;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
        TreePath[] paths = tree.getSelectionPaths();
        if (paths != null) {
            for (TreePath path : paths) {
                expandAll(tree, path);
            }
        }
    }

    public static void expandAll(Tree tree, TreePath parent) {
        TreeNode node = (TreeNode) parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration<?> e = node.children(); e.hasMoreElements(); ) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                expandAll(tree, path);
            }
        }

        tree.expandPath(parent);
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return ActionUpdateThread.BGT;
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        boolean enabled = false;
        TreePath[] paths = tree.getSelectionPaths();
        if (paths != null) {
            for (TreePath path : paths) {
                JackJsonTreeNode node = (JackJsonTreeNode) path.getLastPathComponent();
                JsonNode jsonNode = node.getJsonNode();
                if (jsonNode.isArray() || jsonNode.isObject()) enabled = true;
            }
        }

        e.getPresentation().setEnabledAndVisible(enabled);
    }
}
